package com.be.beadmin.device.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.be.beadmin.common.exception.BeadminException;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class ExcelListener<T> extends AnalysisEventListener<T> {

    private List<T> cachedDataList =  ListUtils.newArrayList();

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        // headMap 包含了 Excel 表头的信息，key 是列的索引，value 是表头内容
        // 检查表头是否匹配预期
        List<String> expectedHeaders = Arrays.asList("设备名称", "设备编号", "生产区域","计量单位","计量周期","计量值","年","月","日","能源介质");
        if (!headMap.values().containsAll(expectedHeaders)) {
            throw new BeadminException("表头信息不匹配，请使用模板上传");
        }
    }

    @Override
    public void invoke(T data, AnalysisContext analysisContext) {
        cachedDataList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }

    /**
     * 返回数据
     *
     * @return 返回读取的数据集合
     **/
    public List<T> getDatas() {
        return cachedDataList;
    }

    /**
     * 设置读取的数据集合
     *
     * @param datas 设置读取的数据集合
     **/
    public void setDatas(List<T> datas) {
        this.cachedDataList = datas;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {

        ReadRowHolder readRowHolder = context.readRowHolder();

        // 获取异常行号
        Integer rowIndex = readRowHolder.getRowIndex();

        // 获取异常表头
//        Map<Integer, Head> headMap = context.readSheetHolder().excelReadHeadProperty().getHeadMap();

        if (exception instanceof BeadminException){
            throw exception;
        }else{
            String message = "第" + (rowIndex+1)+ "行数据解析异常:" + exception.getMessage() ;
            throw new BeadminException(message);
        }
    }
}
